package com.learn.security.app.service.impl;

import com.learn.security.app.service.LoginService;
import com.learn.security.config.SecurityConfigProperties;
import com.learn.security.domain.entity.Login;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;
import java.util.regex.Matcher;

/**
 * @author PC
 * UserDetails实现类
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    private LoginService loginService;

    private PasswordEncoder passwordEncoder;

    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Autowired
    private void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    private void setSecurityConfigProperties(SecurityConfigProperties securityConfigProperties) {
        this.securityConfigProperties = securityConfigProperties;
    }

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        // 1. 查询用户
        Login loginInfo = loginService.getLoginInfo(loginName);
        if (loginInfo == null) {
            //这里找不到必须抛异常
            throw new UsernameNotFoundException("User " + loginName + " was not found in db");
        }

        //2. 获取并加密密码
        Assert.isTrue(StringUtils.isNotEmpty(loginInfo.getPassword()), "password deletion");
        String password = loginInfo.getPassword();
        //数据库中可能有一些未加密的密码（之前测试用），这部分在校验的时候需要加密校验，其实可以在注册的时候加一下校验
        Matcher matcher = securityConfigProperties.getEncryptPattern().matcher(loginInfo.getPassword());
        if (!matcher.matches()) {
            password = passwordEncoder.encode(loginInfo.getPassword());
        }

        //3. 赋予user账户一个或多个权限，用逗号分隔，测试可以使用用户名，正式需添加权限字段
        List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(loginName);

        return new User(loginName, password, grantedAuthorityList);
    }
}

